package vn.egame.elockscreen.activity;

import vn.egame.elockscreen.ELockscreenPreferences;
import vn.egame.elockscreen.OnUnlockListener;
import vn.egame.elockscreen.R;
import vn.egame.elockscreen.service.ScreenLockerService;
import vn.egame.elockscreen.view.LockscreenAniamtionView;
import vn.egame.elockscreen.view.TimeView;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.Toast;

@SuppressLint("NewApi")
public class LockScreenAnimationActivity extends FragmentActivity implements
		OnUnlockListener {

	private Context mContext;

	private boolean inResume;
	private RelativeLayout mRTimeView;
	int Measuredwidth = 0;
	int Measuredheight = 0;

	Dialog dlg;
	LockscreenAniamtionView gameView;

	public void getScreenSize() {
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		Measuredheight = displaymetrics.heightPixels;
		Measuredwidth = displaymetrics.widthPixels;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (!ScreenLockerService.isRunning) {

			// Calendar cal = Calendar.getInstance();
			//
			// Intent intent = new Intent(this, ScreenLockerService.class);
			// PendingIntent pintent = PendingIntent
			// .getService(this, 0, intent, 0);
			//
			// AlarmManager alarm = (AlarmManager)
			// getSystemService(Context.ALARM_SERVICE);
			// // Start every minute
			// alarm.setRepeating(AlarmManager.RTC_WAKEUP,
			// cal.getTimeInMillis(),
			// 1000, pintent);

			ScreenLockerService.startActionStart(this, null, null);

		}

		this.getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

		// ScreenLockerService.isShowLock = true;

		ELockscreenPreferences.getInstance().initPreferences(
				getApplicationContext());
		// ELockscreenPreferences.getInstance().setEnablePasscode(true);
		// ELockscreenPreferences.getInstance().setValuePasscode("1234");

		Log.d("Kai", "LockScreenActivity onCreate");

		// startService(new Intent(this, Servicelock.class));

		// getStartType(getIntent());

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.activity_aniamtion_lockscreen);

		final View decorView = getWindow().getDecorView();
		decorView
				.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
					@Override
					public void onSystemUiVisibilityChange(int i) {
						int height = decorView.getHeight();

					}
				});

		// toggleHideyBar();

		getScreenSize();

		mRTimeView = (RelativeLayout) findViewById(R.id.r_timeview);

		TimeView mTimeView = new TimeView(getApplicationContext());
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		mRTimeView.addView(mTimeView, params);

		gameView = (LockscreenAniamtionView) findViewById(R.id.gameView);
		gameView.setUnlockListener(this);

		((LockApplication) getApplication()).isLockScreenShowing = true;

	}

	public void toggleHideyBar() {

		// BEGIN_INCLUDE (get_current_ui_flags)
		// The UI options currently enabled are represented by a bitfield.
		// getSystemUiVisibility() gives us that bitfield.
		int uiOptions = getWindow().getDecorView().getSystemUiVisibility();
		int newUiOptions = uiOptions;
		// END_INCLUDE (get_current_ui_flags)
		// BEGIN_INCLUDE (toggle_ui_flags)
		boolean isImmersiveModeEnabled = ((uiOptions | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) == uiOptions);

		// Navigation bar hiding: Backwards compatible to ICS.
		if (Build.VERSION.SDK_INT >= 14) {
			newUiOptions ^= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
		}

		// Status bar hiding: Backwards compatible to Jellybean
		if (Build.VERSION.SDK_INT >= 16) {
			newUiOptions ^= View.SYSTEM_UI_FLAG_FULLSCREEN;
		}

		// Immersive mode: Backward compatible to KitKat.
		// Note that this flag doesn't do anything by itself, it only augments
		// the behavior
		// of HIDE_NAVIGATION and FLAG_FULLSCREEN. For the purposes of this
		// sample
		// all three flags are being toggled together.
		// Note that there are two immersive mode UI flags, one of which is
		// referred to as "sticky".
		// Sticky immersive mode differs in that it makes the navigation and
		// status bars
		// semi-transparent, and the UI flag does not get cleared when the user
		// interacts with
		// the screen.
		if (Build.VERSION.SDK_INT >= 18) {
			newUiOptions ^= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
		}

		getWindow().getDecorView().setSystemUiVisibility(newUiOptions);
		// END_INCLUDE (set_ui_flags)
	}

	public static boolean isXLargeScreen(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
	}

	public static Bitmap drawableToBitmap(Drawable drawable) {
		if (drawable instanceof BitmapDrawable) {
			return ((BitmapDrawable) drawable).getBitmap();
		}

		Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
				drawable.getIntrinsicHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
		drawable.draw(canvas);

		return bitmap;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		// if (!inResume && ScreenLockerService.isScreenOn) {
		// Animation hyperspaceJump = AnimationUtils.loadAnimation(this,
		// R.anim.scale);
		// mImgBg.startAnimation(hyperspaceJump);
		// inResume = true;
		// }
		//
		// if (ScreenLockerService.isScreenOn) {
		// Toast.makeText(getApplicationContext(), "screen is on",
		// Toast.LENGTH_SHORT).show();
		// }

		super.onResume();

		// mHomeKeyLocker.lock(this);
		// toggleHideyBar();

		// onCancelUnlock();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		// mHomeKeyLocker.lock(this);

	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		// if (!hasFocus) {
		// ActivityManager am = (ActivityManager)
		// getSystemService(Context.ACTIVITY_SERVICE);
		// am.moveTaskToFront(getTaskId(), ActivityManager.MOVE_TASK_WITH_HOME);
		// sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
		// }

		if (!hasFocus) {
			Log.d("Focus debug", "Lost focus !");

			Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
			sendBroadcast(closeDialog);
		}

		// toggleHideyBar();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		// mHomeKeyLocker.unlock();

		super.onDestroy();
	}

	@Override
	public void onAttachedToWindow() {
		// TODO Auto-generated method stub

		super.onAttachedToWindow();
	}

	// public void setUnlock() {
	// vibrator.vibrate(500);
	// finish();
	// }

	@Override
	public void onUnlock() {
		// TODO Auto-generated method stub
		// dlg.dismiss();
		// ScreenLockerService.isShowLock = false;

		if (ELockscreenPreferences.getInstance().isEnablePasscode()) {
			startActivityForResult(new Intent(getApplicationContext(),
					PasscodeActivity.class), 2);
		} else {
			// ScreenLockerService.isShowLock = false;
			((LockApplication) getApplication()).isLockScreenShowing = false;
			finish();
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// check if the request code is same as what is passed here it is 2
		if (requestCode == 2) {
			String message = data.getStringExtra("MESSAGE");
			if (message.equals("CANCEL")) {
				gameView.resetState();
			} else if (message.equals("STOP")) {
				((LockApplication) getApplication()).isLockScreenShowing = false;
				finish();
			}
		}

	}

	@Override
	public void onStateChange() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCancelUnlock() {
		// TODO Auto-generated method stub

	}

	public void onConfirmPasscode() {
		startActivity(new Intent(getApplicationContext(),
				PasscodeActivity.class));
		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// super.onKeyDown(keyCode, event);
		// switch (keyCode) {
		// case KeyEvent.KEYCODE_CAMERA:
		// Toast.makeText(this, "Pressed Camera Button", Toast.LENGTH_SHORT)
		// .show();
		// return true;
		// case KeyEvent.KEYCODE_1:
		// Toast.makeText(this, "Pressed 1", Toast.LENGTH_SHORT).show();
		// return true;
		// case KeyEvent.KEYCODE_HOME:
		// Toast.makeText(this, "Pressed Home Button", Toast.LENGTH_SHORT)
		// .show();
		// return true;
		//
		// case KeyEvent.KEYCODE_BACK:
		// Toast.makeText(this, "Pressed Back Button", Toast.LENGTH_SHORT)
		// .show();
		// finish();
		// return true;
		// }

		return false;
	}
}
